"use strict";
const path = require("path");
const config = require("./src/utils/config.js");

// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const AliyunossWebpackPlugin = require("aliyunoss-webpack-plugin");
const aliyunUploadPlugin = new AliyunossWebpackPlugin({
  buildPath: "dist/test1_h5/**",
  region: "oss-cn-beijing",
  accessKeyId: "LTAI5t9vMfpS1m1CkRCARwAy",
  accessKeySecret: "gT04svewlGzP8sWGzQMgH5h2r61PcK",
  bucket: "tarot-test",
  deleteAll: false,
  generateObjectPath: function (filename, file) {
    return file.replace(/dist\/test1_h5\//, "test1_h5/");
  }
});

const S3WebpackPlugin = require("aws-s3-webpack-plugin");
const s3WebpackPlugin = new S3WebpackPlugin({
  buildPath: "dist/test1_h5/**",
  region: "us-east-1",
  accessKeyId: "AKIAZ2F76BMJYPL3QHNO",
  secretAccessKey: "fVUrP2oXPrcMXGSYXZBXVvBvSleh60DAA2UIn9zd",
  bucket: "tarot-s3",
  generateObjectPath: function (filename, file) {
    return file.replace(/dist\/test1_h5\//, "test1_h5/");
  }
})

// const bundleAnalyzerPlugin = new BundleAnalyzerPlugin()

function resolve (dir) {
  return path.join(__dirname, dir);
}

const title = config.title || "Test"; // page title

module.exports = {
  lintOnSave: false,//关闭语法检查
  publicPath: process.env.NODE_ENV === 'development' ? "/" : config.imgHost + "test1_h5/",
  outputDir: "dist/test1_h5",
  assetsDir: "static",
  productionSourceMap: false,
  devServer: {
    disableHostCheck: true,
    open: true, //是否自动弹出浏览器页面
    host: '0.0.0.0', // 允许所有设备访问（默认仅 localhost）
    port: 8888, // 端口号
    hot: true,
    overlay: {
      warnings: false,
      errors: true
    }
  },
  configureWebpack: {
    name: title,
    output: {
      filename: `js/[name].[hash].js`,
      chunkFilename: `js/[name].[hash].js`
    },
    externals: {
      vue: "Vue",
      "vue-router": "VueRouter"
    },
    resolve: {
      symlinks: true,
      alias: {
        "@": resolve("src"),
        'vue$': 'vue/dist/vue.esm.js'
      }
    },
    plugins: [
      process.env.NODE_ENV != 'development' && (process.env.VUE_APP_IS_RELEASE == 0 ? aliyunUploadPlugin : s3WebpackPlugin),
      // bundleAnalyzerPlugin,
      // 开启分离 js
    ].filter(Boolean),
  },
  chainWebpack (config) {
    config.entry("main").add("babel-polyfill");
    config.plugins.delete("preload"); // TODO: need test
    config.plugins.delete("prefetch"); // TODO: need test
    // set svg-sprite-loader
    config.module
      .rule("svg")
      .exclude.add(resolve("src/icons"))
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      })
      .end();
    config.when(process.env.NODE_ENV !== "development", config => {
      config
        .plugin("ScriptExtHtmlWebpackPlugin")
        .after("html")
        .use("script-ext-html-webpack-plugin", [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end();
      config.optimization.splitChunks({
        chunks: "all",
        cacheGroups: {
          lottie: {
            test: /[\\/]node_modules[\\/]lottie-web[\\/]/, // 匹配 lottie 库
            name: 'lottie', // 拆分出的包的名称
            priority: 20, // 提高优先级，确保优先拆分
            enforce: true // 强制拆分
          },
          libs: {
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial" // only package third parties that are initially dependent
          },
          commons: {
            name: "chunk-commons",
            test: resolve("src/components"), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      });
      config.optimization.runtimeChunk("single");
      // 清除 console.log
      // config.optimization.minimizer('terser').tap((args) => {
      //   args[0].terserOptions.compress.drop_console = true
      //   return args
      // })
    });
  }
};
